package com.yehuo.app.controller;


import com.alibaba.druid.util.StringUtils;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.yehuo.app.entity.UserWX;
import com.yehuo.app.mapper.OrderMapper;
import com.yehuo.app.mapper.UserMapper;
import com.yehuo.app.mapper.UserWXMapper;
import com.yehuo.app.model.APP;
import java.math.BigDecimal;
import java.util.HashMap;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

@RestController
@RequestMapping("/wx/user")
public class WXController {
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private OrderMapper orderMapper;
    @Autowired
    private RestTemplate restTemplate;
    @Value("${wechat.pay.appId}")
    private String appid;
    @Value("${wechat.pay.appSecret}")
    private String secret;
    @Value("${wechat.getAccess_token}")
    private String getAccess_token;
    @Value("${wechat.getUserInfo}")
    private String getUserInfo;
    @Autowired
    private UserWXMapper userWXMapper;

    @PostMapping({"/granWx"})
    public APP granWx(String userId,String code) throws Exception {
        if (StringUtils.isEmpty(code)) {
            return APP.fail("请授权登录微信:code:"+code +"为null",null);
        } else {
            String url = this.getAccess_token + "?appid=" + this.appid
                    + "&secret=" + this.secret
                    + "&code=" + code + "&grant_type=authorization_code";
            ResponseEntity<String> responseEntity = this.restTemplate.getForEntity(url,String.class);
            Map result = JSON.parseObject(responseEntity.getBody());
            Object errcode = result.get("errcode");
            if (StringUtils.isEmpty(errcode + "")) {
                return APP.fail("获取openId失败,原因" + result.get("errmsg").toString(),null);
            }
            url = this.getUserInfo + "?access_token=" + result.get("access_token")
                    + "&openid=" + result.get("openid");
            responseEntity = this.restTemplate.getForEntity(url, String.class);
            result = JSON.parseObject(responseEntity.getBody());
            errcode = result.get("errcode");
            if (StringUtils.isEmpty(errcode + "")) {
                return APP.fail("获取用户信息失败,原因" + result.get("errmsg").toString(),null);
            }
            System.out.println(result);
            QueryWrapper<UserWX> queryWrapper = new QueryWrapper();
            queryWrapper.eq("user_id", userId);
            UserWX userWX = (UserWX)this.userWXMapper.selectOne(queryWrapper);
            UserWX newUserWx = JSON.parseObject(result.toString(),UserWX.class);
            if (userWX != null) {
                newUserWx.setId(userWX.getId());
                userWXMapper.updateById(newUserWx);
            } else {
                newUserWx.setUserId(userId);
                userWXMapper.insert(newUserWx);
            }
            //保存
            return APP.success("微信用户登录成功",newUserWx);
        }
    }

    @PostMapping({"/saveWx"})
    public APP granWx(UserWX userWX) throws Exception {
        if (StringUtils.isEmpty(userWX.getUserId())) {
            return APP.fail("用户id 为空", null);
        } else {
            QueryWrapper<UserWX> queryWrapper = new QueryWrapper();
            queryWrapper.eq("user_id", userWX.getUserId());
            UserWX userWX1 = (UserWX)this.userWXMapper.selectOne(queryWrapper);
            if (userWX1 != null) {
                userWX.setId(userWX1.getId());
                this.userWXMapper.updateById(userWX);
            } else {
                this.userWXMapper.insert(userWX);
            }
            return APP.success("添加微信授权信息成功", userWX);
        }
    }

    @PostMapping({"/getWx"})
    public APP getWx(String userId) throws Exception {
        APP app = new APP();
        QueryWrapper<UserWX> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("user_id",userId);
        UserWX userWX = this.userWXMapper.selectOne(queryWrapper);
        if (userWX == null) {
            app.setCode(500);
            app.setMsg("请授权登录微信");
            return app;
        } else {
            return APP.success("获取微信用户数据成功", userWX);
        }
    }

    public static int changeY2F(String amount) {
        return (new BigDecimal(amount)).multiply(new BigDecimal(100)).intValue();
    }

    public static String getIpAddress(HttpServletRequest request) {
        String ip = request.getHeader("x-forwarded-for");
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("Proxy-Client-IP");
        }

        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("WL-Proxy-Client-IP");
        }

        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("HTTP_CLIENT_IP");
        }

        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("HTTP_X_FORWARDED_FOR");
        }

        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getRemoteAddr();
        }

        return ip;
    }
}